import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserInfo, getEmployeeInfo } from '@/api/user'
import { Message } from 'element-ui'
const state = () => ({
  token: getToken(),
  userInfo: {}
})

const mutations = {
  SETTOKEN(state, payload) {
    state.token = payload
    setToken(payload)
  },
  REMOVETOKEN(state) {
    state.token = null
    removeToken()
  },
  // 设置用户信息
  SETUSERINFO(state, payload) {
    state.userInfo = payload
  },
  // 删除用户信息
  REMOVEUSERINFO(state) {
    state.userInfo = {}
  }
}

const actions = {
  async login(ctx, data) {
    const res = await login(data)
    // console.log('store/user', res)
    if (res) {
      ctx.commit('SETTOKEN', res)
      Message.success('登录成功')
    }
  },
  // 退出登录，清除token和用户信息
  logout(ctx) {
    ctx.commit('REMOVETOKEN')
    ctx.commit('REMOVEUSERINFO')
  },

  // 获取用户资料
  async getUserInfo(ctx) {
    const res1 = await getUserInfo()
    const res2 = await getEmployeeInfo(res1.userId)
    const res3 = { ...res1, ...res2 }
    ctx.commit('SETUSERINFO', res3)
    return res3
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

